package com.haixee.parkdemo.custom.service.impl;

import com.haixee.parkdemo.common.context.WebContextHolder;
import com.haixee.parkdemo.custom.dao.UserScopeCustomMapper;
import com.haixee.parkdemo.custom.model.UserScope;
import com.haixee.parkdemo.custom.service.UserScopeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Service
public class UserScopeServiceImpl implements UserScopeService {

    @Autowired
    private UserScopeCustomMapper userScopeCustomMapper;


    @Override
    @Transactional
    public Integer insertBeforeCheck(Integer uid) {

        List<Integer> curDeptList = WebContextHolder.getAuth().getDeptIdList();

        Integer maxVer = userScopeCustomMapper.selectMaxUserVer(uid);
        Set<Integer> deptSet = userScopeCustomMapper.selectOptDeptByUidAndUidVer(uid, maxVer);

        boolean needSet = false;
        if (curDeptList.size() == deptSet.size()) {

            for (Integer curDept : curDeptList) {
                if (!deptSet.contains(curDept)) {
                    needSet = true;
                    break;
                }
            }
        } else {
            needSet = true;
        }


        if (!needSet) {
            return maxVer;
        }

        maxVer++;
        List<UserScope> scopeList = new ArrayList<>(curDeptList.size());
        for (Integer curDept : curDeptList) {
            UserScope userScope = new UserScope();
            userScope.setOptDept(curDept);
            userScope.setUid(uid);
            userScope.setUidVer(maxVer);
            userScope.setTenantId(WebContextHolder.getAuth().getTenantId());
            scopeList.add(userScope);
        }

        userScopeCustomMapper.insertMany(scopeList);

        return maxVer;
    }

    @Override
    public List<Integer> getScope(Integer uid, List<Integer> underDeptList) {

        Byte roleScope = WebContextHolder.getAuth().getRoleScope();
        if (roleScope == 3) {
            return null;
        } else if (roleScope == 1) {
            return userScopeCustomMapper.selectScope(uid, underDeptList);
        } else {
            return userScopeCustomMapper.selectScope(null, underDeptList);
        }
    }
}
